<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const rootList = [
      {id: 1, pid: 0, text: '菜单1'},
      {id: 11, pid: 1, text: '菜单1-1'},
      {id: 12, pid: 1, text: '菜单1-2'},
      {id: 2, pid: 0, text: '菜单2'},
      {id: 21, pid: 2, text: '菜单2-1'}
    ]

    function getTreeList(rootList, id, list) {
      for (let item of rootList) {
        if(item.pid == id) {
          list.push(item)
        }
      }
      
      for (let i of list) {
        // debugger
        i.children = []
        getTreeList(rootList, i.id, i.children)
        if(i.children.length === 0) {
          delete i.children
        }
      }
      return list
    } 
    
    const res = getTreeList(rootList, 0, [])
    console.log('res', res)
  </script>
</body>
</html>